package org.adorsys.aderp.aderplogin.client.hessian;

import java.net.URL;
import java.net.URLConnection;

import org.adorsys.aderp.aderplogin.client.common.TokenProvider;
import org.apache.commons.lang3.StringUtils;

import com.caucho.hessian.client.HessianConnection;
import com.caucho.hessian.client.HessianProxy;
import com.caucho.hessian.client.HessianProxyFactory;

public class HessianTokenInCookieProxy  extends HessianProxy {
	
	private static final long serialVersionUID = 1L;
	private TokenProvider tokenProvider;
	
	private String cookieTokenName;
	
    HessianTokenInCookieProxy(HessianProxyFactory factory, URL url) {
        super(url, factory);
    }

    @Override
    protected void parseResponseHeaders(URLConnection conn) {    	
    	// noop
    }

    @Override
	protected void addRequestHeaders(HessianConnection conn) {
    	String token = tokenProvider.getToken();
    	if(StringUtils.isBlank(token)) return;
    	
    	conn.addHeader("Cookie", formatCookie(cookieTokenName, token));

    	super.addRequestHeaders(conn);
	}

	public void setTokenProvider(TokenProvider tokenProvider) {
		this.tokenProvider = tokenProvider;
	}

	public void setCookieTokenName(String cookieTokenName) {
		this.cookieTokenName = cookieTokenName;
	}

	private String formatCookie(String cookieName, String cookieValue){
		return cookieName+"="+cookieValue;
	}
}
